package com.apes.framework.plugin.form.parser.matcher;

import com.apes.framework.jpa.spec.model.Filter;
import com.apes.framework.util.Operation;
import com.apes.framework.util.Tools;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 功能：Filter
 *
 * @author xul
 * @create 2018-07-19 11:09
 */
public class FilterMatcher implements Matcher<String, Filter> {

    private Matcher parent;

    /**
     * 功能：获取识别模式
     */
    @Override
    public String getRegex() {
        return ",";
    }

    @Override
    public Matcher getParent() {
        return parent;
    }

    @Override
    public void setParent(Matcher parent) {
        this.parent = parent;
    }

    /**
     * 功能：元素解析
     *
     * @param content
     */
    @Override
    public Filter parse(String content) {
        String[] values = content.split(getRegex());
        if (values.length < 3) throw new RuntimeException("表达式：" + content + "输入错误！");
        Filter filter = new Filter();
        String left = values[0].trim().replace("'", "");
        filter.setField(left);

        String operation = values[1].trim().replace("'", "");
        if (Tools.isNull(Operation.getSearchType(operation))) throw new RuntimeException("表达式：" + content + "输入错误！");
        filter.setOperator(Operation.getSearchType(operation));

        if (operation.equals("in") || operation.equals("not in")) {
            List list = new ArrayList();
            for (int i = 2; i < values.length; i++) {
                list.add(getValue(values[i].trim()));
            }
            filter.setValue(list.toArray(new String[list.size()]));
        } else {
            filter.setValue(getValue(values[2].trim()));
        }
        return filter;
    }

    private Object getValue(String value) {
        if (value.contains("'")) return value.replace("'", "");
        if (value.toLowerCase().equals("true") || value.toLowerCase().equals("false")) return Boolean.valueOf(value);
        return Double.valueOf(value);
    }
}
